package com.xbjtech.service.impl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Service;

import com.xbjtech.service.SmsService;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SmsServiceLogImpl implements SmsService {

	static Map<String, String> smsTemps = new HashMap<>();
	static {
		smsTemps.put("475461", "【安徽修补匠】订单{$orderId}已指派到您的门店：{$orderInfo}，完工后请提交验证码申请完工，请您主动联系车主，预约时间安装。谢谢");
		smsTemps.put("475460", "【安徽修补匠】验证码{$code}，尊敬的车主，您的订单已安排到如下安装店：{$name}，预约电话：{$phone}，地址：{$address"
				+ "}。请提前一天致电安装店预约，完工后请自行检查爱车。");
	}

	@Override
	public void sendMsg(String smsModelId, String mobile, Map<String, String> params) {
		String regPhone = "^(86)?1[3456789][0-9]{9}$";
		if (!mobile.matches(regPhone)) {
			System.out.println("手机号码：" + mobile + "有误，短信发送失败！");
			return;
		}
		MobilePhone mobilePhone = new MobilePhone();
		mobilePhone.setPhoneNumber(Long.parseLong(mobile));
		String msgContent = getMsgContent(smsModelId, params);
		String smscenterNumber = "1065500053100" + (int) (Math.random() * 10000);
		mobilePhone.showMessage(msgContent, smscenterNumber);
	}

	private String getMsgContent(String smsModelId, Map<String, String> params) {
		String templete = smsTemps.get(smsModelId);
		Set<String> paraNames = params.keySet();
		for (String name : paraNames) {
			templete = templete.replaceAll("\\{\\$" + name + "}", params.get(name));
		}
		return templete;
	}

	@Data
	public class MobilePhone {
		private Long phoneNumber;
		private int width = 20;// 显示屏一行多少汉字
		private int height = 6;// 显示屏一屏多少行
		private String[] screen = new String[height];// 屏幕显示区域，上下加边框

		public void showMessage(String msg, String fromNumber) {
			// 短信内容
			for (int i = 0; i <= msg.length() / width; i++) {
				int endIndex = (i + 1) * width;
				if (endIndex > msg.length()) {
					endIndex = msg.length();
					screen[i] = msg.substring(i * width, endIndex);
					screen[i] = "      " + screen[i] + "  ";
					break;
				}
				screen[i] = msg.substring(i * width, endIndex);
				screen[i] = "      " + screen[i] + "  ";
			}
			log.info("------------" + "收短信号码：" + phoneNumber + "------------");
			log.info("来自：" + fromNumber); // 来信人号码
			log.info("时间：" + new SimpleDateFormat("M-dd hh:mm").format(System.currentTimeMillis()));// 接收短信时间
			log.info("-------------------短信开始------------------");
			for (int i = 0; i < height; i++) {
				log.info(screen[i] == null ? "" : screen[i]);
			}
			log.info("-------------------短信结束------------------");
		}

	}

}
